from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.monitor_metrics.models.prom_department import PromDepartment
from app.monitor_metrics.models.prom_host_group import PromHostGroup


class PromDepartmentHandler():
    """  Department Handler
    """
    def __init__(self):
        pass


    def get_department_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配, 获取部门信息
        """
        try:
            field_info = {field: value}
            order_info = {"name": "asc"}
            result = PromDepartment.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.warning(f"get department search, result is null => {field}:{value}")
                return False, None
        except Exception as e:
            message = f"get department search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result


    def get_department_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配, 获取部门信息
        """
        try:
            result = PromDepartment.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.warning(f"get department match, result is null => {field}:{value}")
                return False
        except Exception as e:
            message = f"get department match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    def add_department(self, db: Session, data: dict):
        """
        创建部门
        """
        try:
            department_object = PromDepartment.get_object_by_name(db, data["name"])
            if department_object:
                # 如果存在， 则异常返回
                logger.error(f"add department failed,{data['name']} was exist")
                return False

            # 创建部门
            result = PromDepartment.add(db, data)
            if not result:
                logger.error(f"add host department to database failed")
                return False
            department_info = PromDepartment.get_object_info_by_name(db, data["name"])
            data["department_uuid"] = department_info["uuid"]

            # 增加部门名称一样的主机组，部门的服务器默认主机组。
            host_group_object = PromHostGroup.get_object_by_name(db, data["name"])
            if not host_group_object:
                result = PromHostGroup.add(db, data)
                if not result:
                    # 创建主机组失败，则把之前创建的部门也清理
                    self.delete_department(db, department_info)
                    logger.error(f"add host group to database failed")
                    return False
        except Exception as e:
            message = f"add department error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def update_department(self, db: Session, data: dict):
        """
        修改部门信息
        """
        try:
            department_object = PromDepartment.get_object_by_uuid(db, data["uuid"])
            if not department_object:
                # 如果不存在， 则异常返回
                logger.error(f"update department failed, uuid:{data['uuid']} not exist")
                return False

            result = PromDepartment.update(db, data)
            if not result:
                logger.error(f"update department to database failed")
                return False
        except Exception as e:
            message = f"update department error "
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def delete_department(self, db: Session, data: dict):
        """
        删除部门信息
        """
        try:
            department_object = PromDepartment.get_object_by_uuid(db, data['uuid'])
            if not department_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete department failed, uuid:{data['uuid']} not exist")
                return False

            host_group_info = PromHostGroup.get_object_info_by_department(db, data['uuid'])
            if len(host_group_info) != 0:
                # 如果不存在， 则异常返回
                logger.error(f"delete department failed, uuid:{data['uuid']} has host_group")
                return False

            # 删除部门信息
            PromDepartment.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete department error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True




